
#include "core.h"
#include "session.h"
#include "connector.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

static int times = 0;
void handleConnection(struct session* session) {
	printf("onConnection\n");
	if (!session) {
		fprintf(stderr, "handle connecton error!!! session is null!!!!\n");
		return;
	}

	char sendBuf[1024 ];
	snprintf(sendBuf, sizeof(sendBuf) - 1, "client data, times is %d", ++times);
	int sendBufLen = strlen(sendBuf);

	int ret = writeSession(session, sendBuf, sendBufLen);
	printf("client send data: %s, ret: %d\n", sendBuf, ret);
}

int handleData(struct session* session) {
	printf("handleData\n");
	if (!session) {
		fprintf(stderr, "hanleData, session is null!!!\n");
		return -1;
	}

	int readBufLen = session->readBufferDataEndPos - session->readBufferDataStartPos;
	if (readBufLen <= 0) {
		printf("in handleData, no data!!!\n");
		return 0;
	}

	char tmp[1024 * 100];
	memcpy(tmp, session->readBuffer + session->readBufferDataStartPos, readBufLen);
	int tmpLen = strlen(tmp);
	session->readBufferDataStartPos += readBufLen;

	printf("%s", tmp);

	writeSession(session, tmp, tmpLen);
	return 0;
}

void handleDisConnection(struct session* session) {
	printf("onDisConnection\n");
}


struct core* c = NULL;
void onSigInt(int sig) {
	printf("onSigInt\n");
	if (c) {
		printf("=========\n");
		//stopCore(c);
		aeStop(c->eventLoop);
	}
}


int main(){

	signal(SIGINT, onSigInt);
	int workThreadNum = 1;
	c = initCore(workThreadNum);
	if (!c) {
		printf("init core error!!\n");
		exit(-1);
	}

	char* serverAddr = "127.0.0.1";
	int serverPort = 80;

	struct connector* con = newConnector(serverAddr,serverPort);
	if (!con) {
		fprintf(stderr, "new connector error!!!\n");
		destroyCore(c);
		exit(-2);
	}

	con->onConnection = handleConnection;
	con->onData = handleData;
	con->onDisConnection = handleDisConnection;

	int ret = startNonBlockConnect(con,  c);
	printf("start non block connect[%d]\n", ret);
	printf("startclient!!!\n");
	eventLoopCore(c );
	printf("endclient!!!!\n");

	destroyCore(c);

	return 0;
}
